'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx, service, app } = this;
    // 动态生成左侧导航菜单, 获取用户权限
    const resource = await service.system.resources.index();

    const userId = ctx.helper.getUserId();
    const result = await ctx.model.Session.findOne({
      where: { user_id: userId }, raw: true,
    });

    const user = await ctx.service.system.accounts.show(userId);

    const urls = result ? result.urls : [];

    let res = [];
    resource.rows.forEach(rows => {
      if ((rows.type === 'page' || rows.type === 'menu') && rows.url !== '/') {
        rows.description = rows.description ? rows.description : rows['router.routerName'];
        rows.url = rows.url ? rows.url : rows['router.path'];
        urls.forEach(url => {
          if (url.url === rows['router.path'] || url.url === null) res.push(rows);
        });
      }
    });

    // 去重
    res = res.filter((item, index, arr) => {
      return arr.indexOf(item) === index;
    });

    res.sort((a, b) => {
      return a.sort - b.sort;
    });

    const new_res = [];
    res.forEach(re => {
      re.icon = re.icon || 'mdi mdi-file-outline'; // 默认页面图标ICON
      if (re.type === 'menu' && re.pid === 0) {
        // 顶级菜单，先预建.
        re.child = [];
        new_res.push(re);
      }
    });

    res.forEach(re => {
      // 生成二级菜单
      if (re.type === 'menu' && re.pid > 0) {
        new_res.forEach(nres => {
          if (nres.id === re.pid) {
            re.child = [];
            nres.child.push(re);
          }
        });
      } else if (re.type === 'page' && re.pid > 0) {
        // 生成三级页面
        new_res.forEach(nres => {
          if (nres.id === re.pid) nres.child.push(re);
          else if (nres.child && nres.child.length > 0) {
            nres.child.forEach(cres => {
              if (cres.id === re.pid) cres.child.push(re);
            });
          }
        });
      }
    });
    // 菜单支持 menu -> page, menu -> menu -> page, 两种形式。

    await ctx.render('/index.tpl', { user, menus: new_res });
  }

  async main() {
    const { ctx } = this;

    await ctx.render('/main.tpl');
  }

  async profile_page() {
    const { ctx } = this;

    const userId = ctx.helper.getUserId();
    const user = await ctx.service.system.accounts.show(userId);

    await ctx.render('/profile.tpl', { user });
  }

  async profile() {
    const { ctx } = this;

    const userId = ctx.helper.getUserId();
    const id = ctx.params.id;
    const data = ctx.request.body;

    ctx.set('Content-Type', 'application/json');
    if( userId !== Number(id) ) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
    } else {
      const field = {};
      for (const key in data) {
        if (data[key]) {
          field[key] = data[key];
        }
      }
      try{
        await ctx.model.User.update(field, { where: { id } });
        ctx.state = 200;
        ctx.body = { code: 200, msg: '更新成功！' };
      }catch(e) {
        ctx.state = 500;
        ctx.body = { code: 500, msg: '更新失败！' + e.message };
      }
    }
  }

  async changePwd_page() {
    const { ctx } = this;

    const userId = ctx.helper.getUserId();
    const user = await ctx.service.system.accounts.show(userId);

    await ctx.render('/change_pwd.tpl', { user });
  }

  async changePwd() {
    const { ctx } = this;

    const userId = ctx.helper.getUserId();
    const id = ctx.params.id;
    const data = ctx.request.body;

    ctx.set('Content-Type', 'application/json');
    if( userId !== Number(id) ) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '参数不正确！' };
    } else {
      const field = {};
      if( data.password !== data.password_again) {
        ctx.state = 403;
        ctx.body = { code: 403, msg: '两次密码不匹配！' + e.message };
        return;
      }
      field.password = ctx.helper.md5(data.password);
      
      try{
        const res = await ctx.model.User.update(field, { where: { id, password: ctx.helper.md5(data.old_password) } });
        if(res[0] === 1) {
          ctx.state = 200;
          ctx.body = { code: 200, msg: '更新成功！' };
        } else {
          ctx.state = 403;
          ctx.body = { code: 403, msg: '旧密码不匹配' + e.message };
        }
      }catch(e) {
        ctx.state = 500;
        ctx.body = { code: 500, msg: '更新失败！' + e.message };
      }
    }
  }
  

  async getCode() {
    const options = {
      width: 120,
      height: 38, // height of captcha
      fontSize: 50, // captcha text size
      color: true,
      ignoreChars: '0oO1ilI',
      noise: 3,
    };
    const svgcaptcha = require('svg-captcha');
    // 生成验证码，并写入session
    const captcha = svgcaptcha.createMathExpr(options);
    // 保存到session
    this.ctx.session.login_code = captcha.text;
    this.ctx.session.maxAge = 1000 * 60 * 10;
    this.ctx.type = 'svg';
    this.ctx.body = captcha.data;
  }
}

module.exports = HomeController;
